package study.zookeeper.controller.curator;

import lombok.extern.slf4j.Slf4j;
import org.apache.curator.framework.CuratorFramework;
import org.apache.curator.framework.recipes.cache.CuratorCache;
import org.apache.curator.framework.recipes.cache.CuratorCacheListener;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.core.env.ConfigurableEnvironment;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import javax.annotation.PostConstruct;

@Slf4j
@RestController
@RequestMapping("/listener")
public class _2ListenerController {

    private String path = "/data/abc";

    @Autowired
    private CuratorFramework client;

    ConfigurableEnvironment environment;

    @PostConstruct
    public void init() {
        //
        CuratorCache cache = CuratorCache.build(client, path);
        //
        CuratorCacheListener listener = CuratorCacheListener.builder()
                .forCreates(node -> {
                    byte[] data = node.getData();
                    log.info(String.format(">>>>>> Node created: [%s]", node));
                })
                .forChanges((oldNode, node) -> {
                    byte[] oldData = oldNode.getData();
                    byte[] data = node.getData();
                    log.info(">>>>>> Node changes: {}", new String(oldData));
                    log.info(">>>>>> Node changes: {}", new String(data));

                })
                .forDeletes(oldNode -> {
                    log.info(String.format(">>>>>> Node deleted. Old value: [%s]", oldNode));
                })
                .forInitialized(() -> {
                    log.info(">>>>>> Cache initialized");
                })
                .build();
        //register the listener
        cache.listenable().addListener(listener);
        //the cache must be started
        cache.start();
    }
}
